﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace BrasilFramework.Controle.Silverlight.Conversores
{

    public class InteiroConversor : TypeConverter
    {

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (culture == null)
                throw new ArgumentNullException("culture");

            if (value == null)
                throw new ArgumentNullException("value");

            return decimal.Parse(value.ToString(), culture);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(string);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
                throw new ArgumentNullException("destinationType");

            if (culture == null)
                throw new ArgumentNullException("culture");

            int? valorTipado = value as int?;
            if (!valorTipado.HasValue || destinationType != typeof(string))
                throw new NotSupportedException();

            return valorTipado.Value.ToString(culture);
        }
    }

    public class DecimalConversor : TypeConverter
    {

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (culture == null)
                throw new ArgumentNullException("culture");

            if (value == null)
                throw new ArgumentNullException("value");

            return decimal.Parse(value.ToString(), culture);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(string);
        }
      
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
                throw new ArgumentNullException("destinationType");

            if (culture == null)
                throw new ArgumentNullException("culture");

            decimal? valorTipado = value as decimal?;
            if (!valorTipado.HasValue || destinationType != typeof(string))
                throw new NotSupportedException();

            return valorTipado.Value.ToString(culture);
        }
    }

}